package com.platform.qujia.service.impl;
import java.math.BigDecimal;
import java.util.Date;

import com.alibaba.fastjson.JSONObject;
import com.platform.qujia.dao.*;
import com.platform.qujia.enums.CardRecordType;
import com.platform.qujia.enums.RechargeTypeEnum;
import com.platform.qujia.pojo.*;
import com.platform.qujia.pojo.dto.CustomerCardUseRecordQueryDTO;
import com.platform.qujia.pojo.vo.RefundResultVO;
import com.platform.qujia.service.CustomerPointsRecordService;
import com.platform.qujia.service.PayOrderService;
import com.platform.qujia.service.PosRefundService;
import com.platform.qujia.service.PresentAmountRecordService;
import com.platform.qujia.utils.*;
import com.platform.qujia.utils.exception.CustomException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * @date 2023/11/13
 */
@Service
public class PosRefundServiceImpl implements PosRefundService {

    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private CustomerCardUseRecordMapper customerCardUseRecordMapper;
    @Autowired
    private OilMapper oilMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${qujia.bgBaseUrl}")
    private String bgBaseUrl;
//    private String bgBaseUrl = "http://localhost:8080";

    @Autowired
    private PresentAmountRecordMapper presentAmountRecordMapper;
    @Autowired
    private CustomerPointsRecordService customerPointsRecordService;

    @Override
    public PayOrder getLastPaidConsumeOrder(String mobilePhone, Integer stationId, Integer consumerId) {
        PayOrder form = new PayOrder();
        form.setCustomerPhone(mobilePhone);
        form.setStationId(stationId);
        LocalDateTime end = LocalDateTime.now();
        LocalDateTime begin = end.minus(1L, ChronoUnit.DAYS);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(LocalDateTimeUtil.YYYY_MM_DD_HH_MM_SS);
        form.setBeginTime(dtf.format(begin));
        form.setEndTime(dtf.format(end));
        form.setStatus("1");
        return getOnePayOrder(form);
    }

    @Override
    public PayOrder getOneOrder(String orderNo, Integer stationId) {
        PayOrder form = new PayOrder();
        form.setOrderNo(orderNo);
        form.setStationId(stationId);
        form.setStatus("1");
        return getOnePayOrder(form);
    }

    @Override
    public CustomerCardUseRecord getLastPaidRechargeOrder(String mobilePhone, Integer stationId, Integer consumerId) {
        CustomerCardUseRecord form = new CustomerCardUseRecord();
        form.setMobilePhone(mobilePhone);
        form.setStationId(stationId);
        form.setStatus("1");
        LocalDateTime end = LocalDateTime.now();
        LocalDateTime begin = end.minus(1L, ChronoUnit.DAYS);
        CustomerCardUseRecordQueryDTO queryDTO = new CustomerCardUseRecordQueryDTO();
        queryDTO.setRecord(form);
        queryDTO.setPayTypes(new String[]{CardRecordType.WX_RECHARGE.getKey(),CardRecordType.POS_RECHARGE.getKey()});
        queryDTO.setBeginTime(begin);
        queryDTO.setEndTime(end);
        return getOneRechargeOrder(queryDTO);
    }

    @Override
    public CustomerCardUseRecord getOneRechargeOrder(String orderNo, Integer stationId) {
        CustomerCardUseRecord form = new CustomerCardUseRecord();
        form.setOrderNo(orderNo);
        form.setStationId(stationId);
        form.setStatus("1");
        CustomerCardUseRecordQueryDTO queryDTO = new CustomerCardUseRecordQueryDTO();
        queryDTO.setRecord(form);
        queryDTO.setPayTypes(new String[]{CardRecordType.WX_RECHARGE.getKey(),CardRecordType.POS_RECHARGE.getKey()});
        return getOneRechargeOrder(queryDTO);
    }

    @Override
    public RefundResultVO refundConsumeOrder(Integer orderId,Integer userId) {
        PayOrder oldOrder = payOrderMapper.selectByPrimaryKey(orderId);
        if (!"1".equals(oldOrder.getStatus())) {
            throw new CustomException("当前订单不能进行退款");
        }
        PayOrder update = new PayOrder();
        update.setOrderId(orderId);
        update.setExaminStatus("1");
        payOrderMapper.updateByPrimaryKeySelective(update);
        PayOrder req = new PayOrder();
        req.setOrderId(orderId);
        long tmp = System.currentTimeMillis();
        ResponseEntity<BGResult> entity = restTemplate.postForEntity(bgBaseUrl + "/station/order/anny/examinRefundSuccess/{0}/{1}?userId={2}",
                req, BGResult.class, tmp,CryptUtil.useMD5("XAh9q" + tmp + "4SSLi").toUpperCase(), userId);
        BGResult body = entity.getBody();
        if (body == null) {
            throw new CustomException(CodeMsg.SERVER_EXCEPTION);
        }
        int code = body.getCode();
        if (code != 200) {
            throw new CustomException(body.getMsg(),code);
        }
        PayOrder payOrder = payOrderMapper.selectByPrimaryKey(orderId);
        if (payOrder != null) {
            RefundResultVO resultVO = new RefundResultVO();
            PresentAmountRecord record = new PresentAmountRecord();
            record.setOrderNo(payOrder.getOrderNo());
            resultVO.setOrderNo(payOrder.getOrderNo());
            resultVO.setAmt(BigDecimal.valueOf(payOrder.getAmt()));
            resultVO.setMobilePhone(MobilePhoneUtil.encryPhone(payOrder.getCustomerPhone()));
            resultVO.setRefundTime(payOrder.getRefundSuccessDate());
            List<PresentAmountRecord> records = presentAmountRecordMapper.queryAllByLimit(record, PageRequest.of(0, 1));
            if (!records.isEmpty()) {
                PresentAmountRecord amountRecord = records.get(0);
                resultVO.setPresentAmt(amountRecord.getPresentAmount());
            }
            CustomerPointsRecord form = new CustomerPointsRecord();
            form.setOrderNo(payOrder.getOrderNo());
            CustomerPointsRecord pointsRecord = customerPointsRecordService.getOne(form);
            if (pointsRecord != null) {
                resultVO.setIntegral(pointsRecord.getIntegral());
            }
            return resultVO;
        }
        return null;
    }

    @Override
    public RefundResultVO refundRechargeOrder(Integer orderId,Integer userId) {
        CustomerCardUseRecord useRecord = customerCardUseRecordMapper.getById(orderId.longValue());
        long tmp = System.currentTimeMillis();
        ResponseEntity<BGResult> entity = restTemplate.getForEntity(bgBaseUrl + "/customer/anny/card/refund/{0}/{1}?id={2}&userId={3}", BGResult.class,
                tmp, CryptUtil.useMD5("XAh9q" + tmp + "4SSLi").toUpperCase(), orderId,userId);
        BGResult body = entity.getBody();
        if (body == null) {
            throw new CustomException(CodeMsg.SERVER_EXCEPTION);
        }
        int code = body.getCode();
        if (code != 200) {
            throw new CustomException(body.getMsg(),code);
        }
        // 后台接口成功
        Object data = body.getData();
        if (data instanceof Number) {
            CustomerCardUseRecord refundRecord = customerCardUseRecordMapper.getById(Long.valueOf(data.toString()));
            if (refundRecord != null) {
                RefundResultVO resultVO = new RefundResultVO();
                resultVO.setOrderNo(refundRecord.getOrderNo());
                resultVO.setMobilePhone(MobilePhoneUtil.encryPhone(refundRecord.getMobilePhone()));
                resultVO.setAmt(refundRecord.getAmt());
                resultVO.setPresentAmt(refundRecord.getPresentAmt());
                CustomerPointsRecord pointsRecord=new CustomerPointsRecord();
                if(useRecord!=null){
                    pointsRecord.setOrderNo(useRecord.getOrderNo());
                    pointsRecord = customerPointsRecordService.getOne(pointsRecord);
                    if(pointsRecord!=null&&pointsRecord.getIntegral()!=null){
                        resultVO.setIntegral(pointsRecord.getIntegral());
                    }
                }
                resultVO.setRefundTime(refundRecord.getCreateTime());
                return resultVO;
            }
        }
        return null;
    }

    private PayOrder getOnePayOrder(PayOrder payOrder){
        PayOrder order = payOrderMapper.getOneBetweenCreatedDateAndCreateDesc(payOrder);
        if (order != null) {
            if (StringUtils.isNotBlank(order.getOilName())) {
                Oil oil = oilMapper.selectOilById(Long.valueOf(order.getOilName()));
                if (oil != null) {
                    order.setOilName(oil.getOilName());
                }
            }
            if (StringUtils.isNotBlank(order.getOilPersonnelId())) {
                SysUser sysUser = sysUserMapper.selectByPrimaryKey(Long.valueOf(order.getOilPersonnelId()));
                if (sysUser != null) {
                    order.setOilPersonnel(sysUser.getUserName());
                }
            }
        }
        return order;
    }

    private CustomerCardUseRecord getOneRechargeOrder(CustomerCardUseRecordQueryDTO queryDTO){
        CustomerCardUseRecord record = customerCardUseRecordMapper.getOneNotPaidRecordBetweenCreateTimeAndCreateDesc(queryDTO);
        if (record != null) {
            if (record.getOperator() != null) {
                SysUser sysUser = sysUserMapper.selectByPrimaryKey(Long.valueOf(record.getOperator()));
                if (sysUser != null) {
                    record.setOperatorName(sysUser.getUserName());
                }
            }
        }
        return record;
    }
}
